package com.sptpc.book.controller;

import com.sptpc.book.controller.request.NewOrderRequest;
import com.sptpc.book.model.Book;
import com.sptpc.book.model.Order;
import com.sptpc.book.service.BookService;
import com.sptpc.book.service.OrderService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private BookService bookService;
    @Autowired
    private OrderService orderService;


//        @PostMapping(value = "/save",consumes = MediaType.APPLICATION_JSON_VALUE)
//        @ResponseBody
//    public Order saveOrder(@RequestBody NewOrderRequest orderRequest){
//        //Long -> Drink
//        List<Book> books = new ArrayList<>();
//        for (Long bookId : orderRequest.getBooks()){
//            books.add(bookService.getBook(bookId));
//        }
//        Book[] booksArray=new Book[books.size()];
//        books.toArray(booksArray);
//        return orderService.saveOrder(orderRequest.getUser(),
//                booksArray);
//    }

    @PostMapping(value = "/save",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ModelAndView saveOrder(HttpSession session, NewOrderRequest orderRequest){
        //Long -> Drink
        List<Book> books = new ArrayList<>();
        for (Long bookId : orderRequest.getBooks()){
            books.add(bookService.getBook(bookId));
        }
        Book[] booksArray=new Book[books.size()];
        books.toArray(booksArray);

//         session购物车
        session.removeAttribute("cart");

        Order order=orderService.saveOrder(orderRequest.getUser(),booksArray);
        ModelAndView mv=new ModelAndView("/user/complete");
        mv.addObject("order",order);
        return mv;
    }

    @GetMapping("/cart")
    public ModelAndView addCart(HttpSession session, @RequestParam Long book) {
        ModelAndView mv = new ModelAndView("user/cart");

        List<Book> cart = (List<Book>) session.getAttribute("cart");
        if (cart == null) {
            cart = new ArrayList<>();
        }
        cart.add(bookService.getBook(book));
        session.setAttribute("cart", cart);

        return mv;
    }
}
